import { Context, Next } from 'koa'
import logger from '../config/logger'
import { CustomError } from '../errors/CustomError'
import dayjs from 'dayjs'

interface MongoError extends Error {
  code: number
  keyValue?: Record<string, any>
}

interface ErrorResponse {
  success: false
  error: {
    code: string
    message: string
    details?: any
    stack?: string
  }
}

function isMongoError(error: any): error is MongoError {
  return error instanceof Error && 'code' in error
}

export const errorHandler = async (ctx: Context, next: Next) => {
  try {
    await next()
  } catch (error) {
    const err = error as Error

    // 记录错误日志
    logger.error('Error occurred:', {
      timestamp: dayjs().format(),
      message: err.message,
      stack: err.stack,
      url: ctx.url,
      method: ctx.method,
      body: ctx.request.body,
      query: ctx.query,
      params: ctx.params,
      userAgent: ctx.headers['user-agent'],
      ip: ctx.ip
    })

    // 处理验证错误 (mongoose validation) - 放在最前面
    if (err.name === 'ValidationError') {
      const validationError = error as any

      if (!validationError.details) {
        ctx.status = 400
        ctx.body = {
          success: false,
          error: {
            code: 'VALIDATION_ERROR',
            message: validationError.message
          }
        }
        return
      }

      const errors = Object.values(validationError.details)
      // 自定义映射字段名到用户友好的名称（可扩展）
      const fieldLabels: Record<string, string> = {
        username: '用户名',
        password: '密码',
        email: '邮箱',
        phone_number: '手机号',
        title: '标题',
        content: '内容',
        name: '名称',
        code: '编码',
        path: '路径',
        role: '角色'
      }

      const formattedDetails = errors.map((err: any) => {
        const field = err.path
        const label = fieldLabels[field] || field
        let message = err.message

        if (message.includes('is required')) {
          message = `${label}不能为空`
        } else if (message.includes('must be unique')) {
          message = `${label}已存在`
        } else if (message.includes('must be a valid email')) {
          message = `${label}格式不正确`
        } else if (message.includes('must be at least')) {
          message = `${label}长度不足`
        }

        return {
          field,
          label,
          message
        }
      })

      ctx.status = 400
      ctx.body = {
        success: false,
        error: {
          code: 'VALIDATION_ERROR',
          message: '用户数据验证失败',
          details: formattedDetails
        }
      }
      return
    }

    // 处理重复键错误
    if (isMongoError(error) && error.code === 11000) {
      ctx.status = 409
      ctx.body = {
        success: false,
        error: {
          code: 'DUPLICATE_KEY_ERROR',
          message: '数据已存在',
          details: error.keyValue || {}
        }
      }
      return
    }

    // 处理自定义错误 - 放在最后
    if (error instanceof CustomError) {
      ctx.status = error.statusCode
      ctx.body = {
        success: false,
        error: {
          code: error.code,
          message: error.message,
          details: error.details
        }
      }
      return
    }

    // 处理其他未预期错误
    ctx.status = 500
    ctx.body = {
      success: false,
      error: {
        code: 'INTERNAL_ERROR',
        message: '服务器内部错误'
      }
    }

    if (process.env.NODE_ENV === 'development') {
      const responseBody: ErrorResponse = ctx.body as ErrorResponse
      responseBody.error.stack = err.stack
    }
  }
}
